package com.ecube.maintenance.biz.apis.impl;

import android.content.Context;

import com.ecube.maintenance.biz.apis.ICityAction;
import com.ecube.maintenance.biz.commons.Constants;
import com.ecube.maintenance.biz.commons.IListItem;
import com.ecube.maintenance.managers.PrefManager;
import com.ecube.maintenance.pojos.AddressInfo;
import com.ecube.maintenance.pojos.CityListInfo;
import com.ecube.maintenance.utils.GsonUtil;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Trible Chen on 2014/9/17.
 */
public class CityAction {

    public static ProxyCityAction proxyCityAction;
    public static List<IListItem<CityListInfo.CityInfo>> getStaticCityList(Context context){
        if ( proxyCityAction == null ){
            proxyCityAction = new ProxyCityAction(context);
            proxyCityAction.getStaticCityList();
        }
        return proxyCityAction.result;
    }

    public static class ProxyCityAction implements ICityAction{
        List<IListItem<CityListInfo.CityInfo>> result;
        Context mContext;
        public ProxyCityAction(Context context) {
            mContext = context;
        }

        @Override
        public List<CityListInfo> getStaticCityList() {
            try {
                String s = IOUtils.toString(mContext.getAssets().open("cityCenter.txt"));
                TypeToken<List<CityListInfo>> citytoken = new TypeToken<List<CityListInfo>>(){};
                List<CityListInfo> cities = GsonUtil.getInfosFromJson(s,citytoken.getType());
                result = new ArrayList<IListItem<CityListInfo.CityInfo>>();
                List<CityListInfo> cityListInfos = cities;
                if ( cityListInfos == null )return null;
                for ( CityListInfo cli : cityListInfos ){
                    List<CityListInfo.CityInfo> cis = cli.getData();
                    if ( cis == null ){
                        cis = new ArrayList<CityListInfo.CityInfo>();
                    }
                    result.add(cli);
                    for (CityListInfo.CityInfo ci : cis ){
                        result.add(ci);
                    }
                    cis.removeAll(result);
                }
                return cities;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

    }
}
